package com.fuli.app.service.Serviceimpl;

import com.fuli.app.common.ActionResult;
import com.fuli.app.common.Pagination;
import com.fuli.app.common.SystemContext;
import com.fuli.app.dao.CurriculumCategoryDao;
import com.fuli.app.dao.CurriculumDao;
import com.fuli.app.dto.CurriculumCategoryDTO;
import com.fuli.app.dto.ImageDTO;
import com.fuli.app.entity.CurriculumCategory;
import com.fuli.app.entity.Image;
import com.fuli.app.enums.Operation;
import com.fuli.app.service.CurriculumCategoryService;
import com.fuli.app.util.EntityUtils;
import com.fuli.app.util.RstUtils;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class CurriculumCategoryServiceImpl implements CurriculumCategoryService {
    @Autowired
    private CurriculumCategoryDao curriculumCategoryDao;
    @Autowired
    private CurriculumDao curriculumDao;

    @Value("${upload.image.path}")
    private String imagePath;
    @Value("${upload.image.dir}")
    private String imageDir;
    @Value("${upload.image.trash}")
    private String imageTrash;

    @Override
    public ActionResult<String> delete(String id) {
        CurriculumCategory po = curriculumCategoryDao.get(id);
        if (po == null)
            return new ActionResult<>(id);
        // RstUtils.nullError(po, id, Operation.FAIL_DEL);
        if (po.getLeaf()) {
            //判断是否有产品
        } else {
            //判断是否有子类别
            int count = curriculumCategoryDao.countByParentId(id);
            if (count > 0)
                return new ActionResult<>(-1, "删除失败，该分类下有子分类");
        }
        if(!StringUtils.isEmpty(po.getImageName())) {
            String destPath = imageTrash + po.getId() + po.getImageName().substring(po.getImageName().lastIndexOf('.'));
            File dest = new File(destPath);
            if (!dest.getParentFile().exists())
                dest.getParentFile().mkdirs();
            File file = new File(po.getAbsolutePath());
            if (file.exists()) {
                if (file.equals(dest)) {
                    file.delete();
                } else {
                    file.renameTo(dest);
                }
            }
        }
        curriculumCategoryDao.delete(id, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<String> update(CurriculumCategoryDTO dto) {
        //判断数据是否存在
        CurriculumCategory po = curriculumCategoryDao.get(dto.getId());
        RstUtils.nullError(po, dto.getId(), Operation.FAIL_UPD);

        if (!dto.getParentId().equals(po.getParentId())) {
            if (!"root".equals(dto.getParentId())) {
                //验证父节点是否存在
                CurriculumCategory parent = curriculumCategoryDao.get(dto.getParentId());
                if (parent == null)
                    return new ActionResult<>(-1, "修改失败，id=" + dto.getParentId() + "的数据不存在");
                if (parent.getLeaf())
                    return new ActionResult<>(-1, "修改失败，id=" + dto.getParentId() + "的数据为叶子节点");
                po.setLevel(parent.getLevel() + 1);
            } else {
                po.setLevel(0);
            }
            Integer max = curriculumCategoryDao.getMaxSortIndex(dto.getParentId());
            max = max == null ? 0 : max + 1;
            po.setSortIndex(max);
        }

        po.setName(dto.getName());
        po.setIntro(dto.getIntro());
        EntityUtils.update(po);
        curriculumCategoryDao.update(po);
        return new ActionResult<>(po.getId());
    }

    @Override
    public ActionResult<CurriculumCategoryDTO> get(String id) {
        CurriculumCategory po = curriculumCategoryDao.get(id);
        RstUtils.nullError(po, id, Operation.FAIL_GET);
        CurriculumCategoryDTO dto = EntityUtils.copyObject(po, CurriculumCategoryDTO.class);
        return new ActionResult<>(dto);
    }

    @Override
    public ActionResult<String> up(String id) {
        CurriculumCategory po = curriculumCategoryDao.get(id);
        if (po == null)
            return new ActionResult<>(-1, "升序失败，不存在id=" + id + "的数据");
        List<CurriculumCategory> poList = curriculumCategoryDao.listByParentId(po.getParentId(), null, null);
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "升序失败，不存在同级分类");
        for (int i = 0; i < poList.size(); i++) {
            if (id.equals(poList.get(i).getId()) && i != 0) {
                poList.set(i, poList.get(i - 1));
                poList.set(i - 1, po);
                break;
            }
        }
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumCategoryDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<String> down(String id) {
        CurriculumCategory po = curriculumCategoryDao.get(id);
        if (po == null)
            return new ActionResult<>(-1, "降序失败，不存在id=" + id + "的数据");
        List<CurriculumCategory> poList = curriculumCategoryDao.listByParentId(po.getParentId(), null, null);
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "降序失败，不存在同级分类");
        for (int i = 0; i < poList.size(); i++) {
            if (id.equals(poList.get(i).getId()) && i != (poList.size() - 1)) {
                poList.set(i, poList.get(i + 1));
                poList.set(i + 1, po);
                break;
            }
        }
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumCategoryDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<List<CurriculumCategoryDTO>> list(String parentId) {
        List<CurriculumCategory> poList = curriculumCategoryDao.listByParentId(parentId, null, null);
        List<CurriculumCategoryDTO> dtoList = EntityUtils.copyList(poList, CurriculumCategoryDTO.class);
        return new ActionResult<>(dtoList);
    }

    @Override
    public ActionResult<Pagination<CurriculumCategoryDTO>> page(String parentId, Integer pageNo, Integer pageSize) {
        Pagination<CurriculumCategoryDTO> pagination = new Pagination<>(pageNo, pageSize);
        if (curriculumCategoryDao.countByParentId(parentId) > 0) {
            List<CurriculumCategory> poList = curriculumCategoryDao.listByParentId(parentId, pagination.getBeginIndex(), pageSize);
            pagination.setRows(EntityUtils.copyList(poList, CurriculumCategoryDTO.class));
        }
        return new ActionResult<>(pagination);
    }

    @Override
    public ActionResult<String> refresh(String id) {
        List<CurriculumCategory> poList = curriculumCategoryDao.listByParentId(id, null, null);
        if (CollectionUtils.isEmpty(poList))
            return new ActionResult<>(-1, "刷新失败，不存在父节点id=" + id + "的子分类");
        //重新设置排序
        for (int i = 0; i < poList.size(); i++) {
            poList.get(i).setSortIndex(i);
        }
        curriculumCategoryDao.batchUpdateSortIndex(poList, SystemContext.getUserId());
        return new ActionResult<>(id);
    }

    @Override
    public ActionResult<List<CurriculumCategoryDTO>> listAll() {
        List<CurriculumCategory> poList = curriculumCategoryDao.listAll();
        return new ActionResult<>(EntityUtils.copyList(poList, CurriculumCategoryDTO.class));
    }

    @Override
    public ActionResult<CurriculumCategoryDTO> add(MultipartFile file, String name, String parentId, String intro, Boolean leaf) {
        CurriculumCategory po = EntityUtils.init(CurriculumCategory.class);
        if (file != null) {
            String filename = file.getOriginalFilename();

            String suffix = filename.substring(filename.lastIndexOf('.'));
            String imageName = po.getId() + suffix;
            po.setImageName(imageName);
            po.setUrl(imagePath + imageName);
            po.setAbsolutePath(imageDir + imageName);

            File dest = new File(po.getAbsolutePath());
            //判断目录是否存在
            if (!dest.getParentFile().exists())
                dest.getParentFile().mkdirs();
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                System.out.println("保存图片异常");
                e.printStackTrace();
            }
        }
        po.setName(name);
        po.setParentId(parentId);
        po.setIntro(intro);
        po.setLeaf(leaf);

        //如果有父节点，则验证父节点是否存在
        if (!"root".equals(po.getParentId())) {
            CurriculumCategory parent = curriculumCategoryDao.get(po.getParentId());
            if (parent == null)
                return new ActionResult<>(-1, "不存在id=" + po.getParentId() + "的父节点");
            if (parent.getLeaf())
                return new ActionResult<>(-1, "id=" + parent.getId() + "的节点是叶子节点无法添加子分类");
            po.setLevel(parent.getLevel() + 1);
        } else {
            po.setLevel(0);
        }
        //获取最大排序
        Integer max = curriculumCategoryDao.getMaxSortIndex(po.getParentId());
        max = max == null ? 0 : max + 1;
        po.setSortIndex(max);

        curriculumCategoryDao.insert(po);
        return new ActionResult<>(EntityUtils.copyObject(po, CurriculumCategoryDTO.class));
    }
}
